package com.jizhangben.controller;


import com.jizhangben.pojo.UserPojo;
import com.jizhangben.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("views/register.jsp").forward(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 转发到注册插入数据
        // 点击注册的时候 获取到用户的参数
        String userId = req.getParameter("userId");
        String userName = req.getParameter("userName");
        String registerPassword = req.getParameter("registerPassword");
        // 用户注册之前根据用户名称查询该用户是否存在如果不存在的情况下才可以注册 如果存在的话就无法注册
        UserPojo userPojo = userService.findByUserId(userId);
        if (userPojo != null) {
            req.setAttribute("errorMsg", "该用户" + userId + ",在数据库中存在无法重复注册！");
            req.getRequestDispatcher("views/register.jsp").forward(req, resp);
            return;
        }
        //用户数据注册
        int register = userService.register(userId,userName, registerPassword);
        if (register <= 0) {
            // 注册失败了   //转发到错误页面
            req.setAttribute("errorMsg", "注册失败!");
            req.getRequestDispatcher("views/register.jsp").forward(req, resp);
            return;
        }
        // 注册成功之后就直接重定向到登录请求
        resp.sendRedirect(req.getContextPath()+"/login");
    }
}

